package com.hero.herocat;

import com.alibaba.fastjson.JSONObject;
import com.hero.servlet.HeroResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.security.InvalidParameterException;

/**
 * @author linhui
 */
public class HttpServletResponse implements HeroResponse {

    private HttpRequest httpRequest;

    private ChannelHandlerContext channelHandlerContext;


    public HttpServletResponse(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext) {
        if (httpRequest == null) {
            throw new InvalidParameterException("HttpRequest can not null");
        }
        if (channelHandlerContext == null) {
            throw new InvalidParameterException("channelHandlerContext can not null");
        }

        this.httpRequest = httpRequest;
        this.channelHandlerContext = channelHandlerContext;
    }

    @Override
    public void write(Object object) throws Exception {
        byte[] bytes = new byte[0];
        if (object instanceof byte[]) {
            bytes = (byte[]) object;
        } else if (object != null) {
            bytes = JSONObject.toJSONBytes(object);
        }
        ///设置响应对象
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, Unpooled.wrappedBuffer(bytes));
        HttpHeaders headers = response.headers();
//        headers.set(HttpHeaderNames.CONTENT_TYPE, "text/json");
        headers.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        headers.set(HttpHeaderNames.EXPIRES, 0);
        if (HttpUtil.isKeepAlive(httpRequest)) {
            headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }

        channelHandlerContext.writeAndFlush(response);


    }

    public void close() {
        channelHandlerContext.close();

    }
}
